import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'

//设置路由
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      //登录页
      name: 'login',
      path: '/login',
      component: () =>  import('@/views/login/loginPage.vue') 
    },
    {
      //主要内容
      name: 'container',
      path: '/',
      component: () => import('@/views/layout/layout.vue') ,
      redirect: '/article/manage',
      //注意懒加载写法，避免出错
      children: [
        {
          path: '/article/manage',
          component: () =>  import('@/views/article/manage.vue') 
        },
        {
          path: '/article/channel',
          component: () =>  import('@/views/article/channel.vue') 
        },
        {
          path: '/user/profile',
          component: () =>  import('@/views/user/profile.vue') 
        },
        {
          path: '/user/avatar',
          component: () =>  import('@/views/user/avatar.vue') 
        },
        {
          path: '/user/password',
          component: () =>  import('@/views/user/password.vue') 
        }
      ]
    },
  ],
})
//访问拦截 路由前置守卫
router.beforeEach((to)=>{
  //本地没有储存token，并且不处于login页面，拦截为登录页
  const useStore = useUserStore()
  if(!useStore.token && to.path!=='/login')return '/login'

  return true
})

export default router
